package com.fanrenqiji.modules.sys.utils;

import com.fanrenqiji.common.service.BaseCommonService;
import com.fanrenqiji.common.utils.SpringContextHolder;
import com.fanrenqiji.common.utils.SystemAuthorizingCacheUtils;
import com.fanrenqiji.modules.sys.dao.AreaDao;
import com.fanrenqiji.modules.sys.dao.MenuDao;
import com.fanrenqiji.modules.sys.dao.OfficeDao;
import com.fanrenqiji.modules.sys.dao.UserDao;
import com.fanrenqiji.modules.sys.entity.*;
import com.fanrenqiji.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.google.common.collect.Lists;
import org.apache.shiro.SecurityUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import java.util.List;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年1月26日 下午2:47:24
 * @description 用户工具类,
 */
public class UserUtils extends BaseCommonService {

    private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
    private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
    private static AreaDao areaDao = SpringContextHolder.getBean(AreaDao.class);
    private static OfficeDao officeDao = SpringContextHolder
            .getBean(OfficeDao.class);

    /**
     * 缓存中的一些key
     */
    public static final String CACHE_USER = "user";
    public static final String CACHE_MENU_LIST = "menuList";
    public static final String CACHE_AREA_LIST = "areaList";
    public static final String CACHE_OFFICE_LIST = "officeList";

    public static final String FIRST_AGENCY = "firstAgency";

    /**
     * 从缓存中读取有效的用户
     *
     * @return
     */
    public static User getUser() {
        Principal principal = (Principal) SecurityUtils.getSubject()
                .getPrincipal();
        if (principal != null) {
            User user = userDao.findOne(principal.getId());
            if (user != null) {
                return user;
            }
            return new User();
        }
        // 如果没有登录，则返回实例化空的User对象。
        return new User();
        /*User user = (User) SystemAuthorizingCacheUtils.getCache(CACHE_USER);
        if (user == null) {
			Principal principal = (Principal) SecurityUtils.getSubject()
					.getPrincipal();
			if (principal != null) {
				user = userDao.findOne(principal.getId());
				SystemAuthorizingCacheUtils.putCache(CACHE_USER, user);
			}
		}
		if (user == null) {
			user = new User();
			SecurityUtils.getSubject().logout();
		}
		return user;*/
    }

    /**
     * 如果有更新移除缓存
     *
     * @param isRefresh
     * @return
     */
    public static User getUser(boolean isRefresh) {
        if (isRefresh) {
            SystemAuthorizingCacheUtils.removeCache(CACHE_USER);
        }
        return getUser();
    }

    /**
     * 获得拥有的菜单权限
     *
     * @return
     */
    public static List<Menu> getMenuList() {
        List<Menu> menuList = Lists.newArrayList();
        User user = getUser();
        if (user.isAdmin()) {
            menuList = menuDao.findAllList();
        } else {
            menuList = menuDao.findByUserId(user.getId());
        }
        return menuList;
    }

    /**
     * 获得登陆用户的区域
     *
     * @return
     */
    public static List<Area> getAreaList() {
        List<Area> areaList = Lists.newArrayList();
        User user = getUser();
        if (user.isAdmin()) {
            areaList = areaDao.findAllList();
        } else {
            areaList = areaDao.findAllChild(user.getOffice().getArea().getId(),
                    "%," + user.getOffice().getArea().getId() + ",%");
        }

        return areaList;
    }

    /**
     * 获得当前用户的岗位
     *
     * @return
     */
    public static List<Office> getOfficeList() {

        User user = getUser();
        DetachedCriteria dc = officeDao.createDetachedCriteria();
        dc.add(dataScopeFilter(user, dc.getAlias(), ""));
        dc.add(Restrictions.eq(Office.DEL_FLAG, Office.DEL_FLAG_NORMAL));
        dc.addOrder(Order.asc("code"));
        return officeDao.find(dc);
    }


    public static User getByLoginName(String username) {
        return userDao.findByLoginName(username);
    }
}
